package com.dingwei.superiordiary.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.AppOpsManagerCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.adapter.AddressBookAdapter;
import com.dingwei.superiordiary.bean.AddressBookBean;
import com.dingwei.superiordiary.bean.PhoneDto;
import com.dingwei.superiordiary.mvp.presenter.AddressBookPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.utils.PhoneUtil;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.L;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author 南柯一梦丶
 * Created time 2018/10/26.
 * Personal signature 余生还长 何必慌张
 * Page description :
 * .::::.
 * .::::::::.
 * :::::::::::
 * ..:::::::::::'
 * '::::::::::::'
 * .::::::::::
 * '::::::::::::::..
 * ..::::::::::::.
 * ``::::::::::::::::
 * ::::``:::::::::'        .:::.
 * ::::'   ':::::'       .::::::::.
 * .::::'      ::::     .:::::::'::::.
 * .:::'       :::::  .:::::::::' ':::::.
 * .::'        :::::.:::::::::'      ':::::.
 * .::'         ::::::::::::::'         ``::::.
 * ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 * '.:::::'                    ':'````..
 */
public class AddressBookActivity extends BaseActivity implements Contract.AddressBookView {

    AddressBookPresenter addressBookPresenter = new AddressBookPresenter(this);

    AddressBookAdapter adapter;
    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.m_recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.no_data_layout)
    RelativeLayout noDataLayout;

    private List<PhoneDto> phoneDtos;

    String[] permissions = {Manifest.permission.READ_CONTACTS};
    // 要申请的权限
    List<String> list = new ArrayList<>();

    @Override
    protected int getContentViewId() {
        return R.layout.activity_phone;

    }

    @Override
    protected void initData() {

    }


    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("读取联系人权限不可用")
                .setMessage("次元Plus需要读取联系人权限获取通讯录好友,请在-应用设置-权限-中，允许次元Plus读取联系人权限")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        startRequestPermission();
//                        showDialogTipUserGoToAppSettting();
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }



    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    private void initViews() {
        PhoneUtil phoneUtil = new PhoneUtil(this);
        phoneDtos = phoneUtil.getPhone();
        addressBookPresenter.initData(phoneDtos);
    }


    @Override
    protected void initView() {
        list.add(Manifest.permission.READ_CONTACTS);
        tvTitle.setText("通讯录好友");
        adapter = new AddressBookAdapter(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addItemDecoration(new DividerDecoration(getResources().getColor(R.color.line), 1));
        mRecyclerView.setAdapter(adapter);

        adapter.attentionInterfaceListener(new AddressBookAdapter.attentionInterFace() {
            @Override
            public void attention(int position) {
                AddressBookBean.DataBean data = adapter.getItem(position);
                int action = 0;
                if (data.attentioned == 0) {
                    action = 1;
                } else {
                    action = 0;
                }
                addressBookPresenter.attention(data.id, position, action);
            }
        });
        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (hasPermission(this,list)){
                initViews();
            }else {
                showDialogTipUserRequestPermission();
            }
        }
    }

    /**
     * 系统层的权限判断
     *
     * @param context     上下文
     * @param permissions 申请的权限 Manifest.permission.READ_CONTACTS
     * @return 是否有权限 ：其中有一个获取不了就是失败了
     */
    public static boolean hasPermission(@NonNull Context context, @NonNull List<String> permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true;
        for (String permission : permissions) {
            String op = AppOpsManagerCompat.permissionToOp(permission);
            if (TextUtils.isEmpty(op)) continue;
            int result = AppOpsManagerCompat.noteProxyOp(context, op, context.getPackageName());
            if (result == AppOpsManagerCompat.MODE_IGNORED) return false;
            result = ContextCompat.checkSelfPermission(context, permission);
            if (result != PackageManager.PERMISSION_GRANTED) return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (hasPermission(context,list)){
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    initViews();
                }else {
                    showDialogTipUserRequestPermission();
                }
            }
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    public void setData(AddressBookBean bean) {
        adapter.clear();
        adapter.addAll(bean.data);
    }

    @Override
    public void attentionSuccess(int position) {
        AddressBookBean.DataBean listBean = adapter.getItem(position);
        if (listBean.attentioned == 0) {
            listBean.attentioned = 1;
        } else {
            listBean.attentioned = 0;
        }
        adapter.notifyDataSetChanged();
        showData("success");
    }

    @Override
    public void fail() {
        showData("fail");
    }

    public void showData(String state) {
        if (state.equals("success")) {
            mRecyclerView.setVisibility(View.VISIBLE);
            noDataLayout.setVisibility(View.GONE);
        } else {
            mRecyclerView.setVisibility(View.GONE);
            noDataLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.img_back)
    public void onViewClicked() {
        finish();
    }
}
